﻿using UnityEngine;
using System.Collections;

namespace Lost{
	public class PlaceGroup : MonoBehaviour {
		[SerializeField] LockKey lockKey;
		[SerializeField] PlaceItem[] placeItems;
		///可放置的物品名
		[SerializeField] string[] itemsNeeded;

		void Awake(){
			if (placeItems == null || placeItems.Length == 0) {
				placeItems = GetComponentsInChildren<PlaceItem> ();
			}
			SetPlaces ();
		}

		/// <summary>
		/// 检查是否放对了位置，即尝试开锁
		/// </summary>
		public void Check () {
			lockKey.CurPassword = GetPlacesValue (placeItems);
			if (lockKey.UseKey ()) {
				//此时已经成功开锁，因而清理现场
				int len = placeItems.Length;
				for (int i = 0; i < len; i++) {
					ItemsManager.iDestroy (placeItems [i].FitItem);
					ItemsManager.iDestroy (placeItems [i]);
				}
				Destroy (this);
			}
		}

		void SetPlaces(){
			foreach (PlaceItem pi in placeItems) {
				pi.ItemsNeeded = itemsNeeded;
				pi.AddListener (Check);
			}
		}
		string GetPlacesValue(PlaceItem[] places){
			string s = "";
			foreach (PlaceItem pi in places) {
				int len = itemsNeeded.Length;
				for (int i = 0; i < len; i++) {
					if (itemsNeeded [i] == pi.PlaceValue) {
						s += i.ToString () + '-';
					}
				}
			}
			return s.Remove (s.Length - 1);
		}
	}
}
